package com.ruoyi.web.controller.system;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysSecurity;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.SysSecuritySetting;
import com.ruoyi.system.service.ISysSecuritySettingsService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.domain.AjaxResult.error;

/**
 * 安全设置
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/securitysettings")
public class SysSecuritySettingsController {

    @Autowired
    private RedisCache redisCache;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysSecuritySettingsService sysSecuritySettingsService;

    @ApiOperation("更新用户安全设置")
    @PostMapping("/saveorupdate")
    public AjaxResult update(@RequestBody SysSecuritySetting sysSecuritySetting) {
        if (sysSecuritySetting == null) {
            return error("安全配置信息为空");
        }
        //根据userid判断时候存在对应数据
        List<Long> addIds = new ArrayList<>();
        List<Long> editIds = new ArrayList<>();
        //分开处理，新增或者修改 判断是不是admin
        if(sysSecuritySetting.getUserId() != null)
        {
            //判断是否是admin
            if(sysSecuritySetting.getUserId() == 1)
            {
                //查询是否部分用户存在配置数据
                List<SysSecuritySetting> all = sysSecuritySettingsService.getAll();
                if(all != null && all.size() > 0)
                {
                    List<Long> ids = all.stream().map(f -> f.getUserId()).collect(Collectors.toList());
                    editIds.addAll(ids);
                    sysSecuritySetting.setUserIds(editIds);
                    //更新todo
                    sysSecuritySettingsService.updateById(sysSecuritySetting);
                }
                    //新增  查询所有用户
                    SysUser user = new SysUser();
                    List<SysUser> list = userService.selectUserList(user);
                    if(list != null && list.size() > 0)
                    {
                        addIds = list.stream().map(m -> m.getUserId()).collect(Collectors.toList());
                        addIds.removeAll(editIds);
                    }
                    //new
                if(addIds != null && addIds.size() > 0)
                {
                    sysSecuritySetting.setUserIds(addIds);
                    sysSecuritySettingsService.insertSecuritySetting(sysSecuritySetting);
                }
            }else{
                SysSecuritySetting sysSecuritySetting1 = sysSecuritySettingsService.selectSecuritySettingByOne(sysSecuritySetting.getUserId());
                if(sysSecuritySetting1 != null)
                {
                    editIds.add(sysSecuritySetting1.getUserId());
                    sysSecuritySetting.setUserIds(editIds);
                    //更新
                    sysSecuritySettingsService.updateById(sysSecuritySetting);
                }else{
                    //新增
                    addIds.add(sysSecuritySetting.getUserId());
                    sysSecuritySetting.setUserIds(addIds);
                    sysSecuritySettingsService.insertSecuritySetting(sysSecuritySetting);
                }
            }
            }

        Map<String, Object> map = new HashMap();
        //更新缓存
        if (sysSecuritySetting.getUserIds() != null && sysSecuritySetting.getUserIds().size() > 0) {
            for (Long useId : sysSecuritySetting.getUserIds()) {
                // 更新缓存有效期
                if (sysSecuritySetting.getLoginProtectTime() != null && sysSecuritySetting.getLoginIsProtect()
                        && sysSecuritySetting.getLoginProtectTime() > 0) {
                    expireTime = sysSecuritySetting.getLoginProtectTime();
                }
                //todo
                Collection<String> keys = redisCache.keys(Constants.LOGIN_TOKEN_KEY + "*");
                for (String key : keys) {
                    LoginUser user = redisCache.getCacheObject(key);
                    //相同
                    if(user.getUserId() == useId)
                    {
                        redisCache.setCacheObject(key, user, expireTime, TimeUnit.MINUTES);
                    }
                }
                //保存成功，存reids
                SysSecurity sysSecurity = new SysSecurity();
                BeanUtils.copyProperties(sysSecuritySetting, sysSecurity);
                redisCache.setCacheObject(Constants.SECURITY_SETTING+useId, sysSecurity);
            }
            return AjaxResult.success();
        } else {
            return AjaxResult.error("保存失败");
        }
    }

    @ApiOperation("查询用户安全设置")
    @GetMapping("/info/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId) {
        SysSecuritySetting sysSecuritySetting = sysSecuritySettingsService.selectSecuritySettingByOne(userId);
        if(sysSecuritySetting == null)
        {
            return AjaxResult.success(new SysSecuritySetting());
        }
        return AjaxResult.success(sysSecuritySetting);
    }

}
